<template>
	<view @touchmove.prevent.stop>
		<uni-popup ref="receivePopup" type="bottom">
			<view class="content">
				<view class="part1">
					<image class="logo-view" :src="$util.img(registerConfig.site_logo)"></image>
					<view class="intro-view">
						<view class="welcome-view">{{registerConfig.site_name}}</view>
						<view class="dec-view">{{registerConfig.site_desc}}</view>
					</view>
				</view>
				<image class="close-view" :src="$util.img('upload/uniapp/h5/login/close_icon@2x.png')" @click="close">
				</image>
				<!-- <view class="img-view">
					<button class="avatar-wrapper" plain="true" type="default" form-type="submit"
						open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<block v-if="avatarUrl">
							<image class="avatar" :src="$util.img(avatarUrl)"></image>
						</block>
						<block v-else>
							<image class="avatar" :src="$util.img('upload/uniapp/h5/login/img_add_icon@2x.png')">
							</image>
						</block>
					</button>
				</view> -->
				<!-- <view class="name-view">
					<input class="name-input" type="nickname" @input="onKeyInput" placeholder-class="placeholder-view"
						placeholder="点击获取或输入昵称" />
				</view> -->
				<view class="name-mobile" v-if="forceBindingMobileControl">
					<button open-type="getPhoneNumber" class="name-input" @getphonenumber="getPhoneNumber">
						<text class="" v-if="mobile">{{ mobile }}</text>
						<text class="placeholder-view" v-else>一键获取手机号</text>
					</button>
				</view>
				<view class="name-view" v-if="forceBindingshopCodeControl && !isauth ">
					<input class="name-input" v-model="invite_code" placeholder-class="placeholder-view"
						placeholder="请输入邀请码" />
				</view>
				<view class="login-but color-base-bg" :class="((forceBindingMobileControl && mobile) || !forceBindingMobileControl) 
				&& (!forceBindingshopCodeControl || (forceBindingshopCodeControl && invite_code)) 
				&& isSelect ? 'active' : 'normal'" @click="saveEvent">立即登录</view>
				<view class="agreement-view">
					<image class="select-image-view" :src="$util.img(select_img)" @click="chanegeSelect"></image>
					<text class="text">我已阅读并同意</text>
					<text class="text agreement" @click="openPopup">服务协议、隐私协议</text>
				</view>
			</view>
		</uni-popup>
		<register-reward ref="registerReward"></register-reward>
		<view @touchmove.prevent>
			<uni-popup ref="registerPopup" type="center" :maskClick="false">
				<view class="conten-box">
					<view class="close"><text class="iconfont iconclose" @click="toClose"></text></view>
					<view class="title">{{ regisiterAgreement.title }}</view>
					<view class="con">
						<scroll-view scroll-y="true" class="con"><rich-text
								:nodes="regisiterAgreement.content"></rich-text></scroll-view>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import registerReward from '../register-reward/register-reward.vue';
	export default {
		name: 'loginPop',
		components: {
			uniPopup,
			registerReward
		},
		data() {
			return {
				avatarUrl: '',
				nickName: '',
				isSelect: false,
				mobile: '',
				registerConfig: {},
				// 小程序获取手机号所需数据
				authMobileData: {
					iv: '',
					encryptedData: ''
				},
				regisiterAgreement: {},
				invite_code: '', //激活码
				isauth: 0
			}
		},
		created() {
			this.getRegisterConfig();
		},
		computed: {
			select_img() {
				if (this.isSelect) {
					return 'upload/uniapp/h5/login/select_icon@2x.png'
				}
				return 'upload/uniapp/h5/login/normal_icon@2x.png'
			},
			forceBindingMobileControl() {
				if (this.registerConfig && this.registerConfig.third_party == 1 && this.registerConfig.bind_mobile == 1)
					return true;
				else return false;
			},
			forceBindingshopCodeControl() {
				if (this.registerConfig && this.registerConfig.is_active_code == 1 && !this.isauth) return true;
				else return false;
			}
		},
		methods: {
			/**
			 * 获取注册配置
			 */
			getRegisterConfig() {
				this.$api.sendRequest({
					url: '/api/register/config',
					success: res => {
						if (res.code >= 0) {
							this.registerConfig = res.data.value;
						}
					}
				});
			},
			async getInviteCode() { //获取推荐人所属店铺码
				if (uni.getStorageSync('suid')) {
					let res = await this.$api.sendRequest({
						url: '/api/member/getInviteCode',
						data: {
							member_id: uni.getStorageSync('suid')
						},
						async: false
					});
					this.invite_code = res.data.invite_code;
				}
			},
			/* 获取微信头像信息临时路径 */
			async onChooseAvatar(e) {

				let temporary_url = e.detail.avatarUrl
				/* 上传本地服务器做头像永久处理 */
				var data = {
					token: uni.getStorageSync('token'),
					app_type: 'weapp',
					app_type_name: '微信小程序'
				}
				this.avatarUrl = await this.$util.upload_file_server(temporary_url, data, 'headimg')
			},
			/* 获取输入框昵称信息 */
			onKeyInput(e) {
				this.nickName = e.target.value
				/* 昵称判断 */
				let str = this.nickName.trim()
				if (str.length == 0) {
					this.$util.showToast('请输入合法的昵称')
					return
				}
				if ((/[^/a-zA-Z0-9\u4E00-\u9FA5]/g).test(str)) {
					this.$util.showToast('请输入中英文和数字')
					return
				}
			},
			/* 立即登录 */
			saveEvent() {
				if ((!this.forceBindingMobileControl || (this
						.forceBindingMobileControl && this.mobile)) && this.isSelect &&
					(!this.forceBindingshopCodeControl || (this.forceBindingshopCodeControl && this.invite_code))) {
					let userwxmpInfo = {
						nickName: this.nickName,
						avatarUrl: this.avatarUrl,
						inviteCode: this.invite_code
					};
					uni.setStorageSync('userwxmpInfo', userwxmpInfo);
					if (this.forceBindingMobileControl) { //绑定手机号登录
						this.bindMobile();
					} else {
						this.authLogin();
					}
				}
			},
			/**
			 * 授权登录
			 */
			authLogin() {
				uni.showLoading({
					title: '登录中'
				});
				let data = uni.getStorageSync('authInfo');

				let userwxmpInfo = uni.getStorageSync('userwxmpInfo');
				data.nickName = userwxmpInfo.nickName;
				data.avatarUrl = userwxmpInfo.avatarUrl;
				data.invite_code = userwxmpInfo.inviteCode ? userwxmpInfo.inviteCode : ''
				if (uni.getStorageSync('suid')) data.suid = uni.getStorageSync('suid');

				this.$api.sendRequest({
					url: '/api/login/auth',
					data,
					success: res => {
						if (res.code >= 0) {
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									uni.removeStorageSync('loginLock');
									uni.removeStorageSync('unbound');
									uni.removeStorageSync('authInfo');
									this.$store.dispatch('getCartNumber');
									this.$store.commit('setToken', res.data.token);

									if (res.data.is_register && this.$refs.registerReward
										.getReward()) {
										this.$refs.registerReward.open();
									}
								}
							});
							setTimeout(() => {
								uni.hideLoading();
								this.close();
							}, 1000);
						} else {
							uni.hideLoading();
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						this.$util.showToast({
							title: '登录失败'
						});
					}
				});
			},
			// 微信小程序强制绑定手机号
			bindMobile() {
				uni.showLoading({
					title: '登录中'
				});
				// 授权数据
				let data = this.authMobileData;
				let authData = uni.getStorageSync('authInfo');
				if (authData) Object.assign(data, authData);
				// 昵称头像数据
				let userwxmpInfo = uni.getStorageSync('userwxmpInfo');
				if (userwxmpInfo.avatarUrl) data.headimg = userwxmpInfo.avatarUrl;
				if (userwxmpInfo.nickName) data.nickname = userwxmpInfo.nickName;
				data.invite_code = userwxmpInfo.inviteCode ? userwxmpInfo.inviteCode : ''

				this.$api.sendRequest({
					url: '/api/tripartite/mobileauth',
					data,
					success: res => {
						if (res.code >= 0) {
							uni.setStorage({
								key: 'token',
								data: res.data.token,
								success: () => {
									uni.removeStorageSync('loginLock');
									uni.removeStorageSync('unbound');
									uni.removeStorageSync('authInfo');
									this.$store.dispatch('getCartNumber');
									this.$store.commit('setToken', res.data.token);
								}
							});
							if (res.data.is_register && this.$refs.registerReward.getReward()) {
								this.$refs.registerReward.open();
							}
							setTimeout(() => {
								uni.hideLoading();
								this.close();
							}, 1000);
						} else {
							uni.hideLoading();
							this.$util.showToast({
								title: res.message
							});
						}
					},
					fail: res => {
						uni.hideLoading();
						this.$util.showToast({
							title: 'request:fail'
						});
					}
				});
			},
			/* 是否勾选协议 */
			chanegeSelect() {
				this.isSelect = !this.isSelect
			},
			/**
			 * 展示注册协议
			 */
			async openPopup() {
				let res = await this.$api.sendRequest({
					url: '/api/register/aggrement',
					async: false
				});
				this.regisiterAgreement = res.data;
				this.$refs.registerPopup.open();
			},
			/**
			 * 点击关闭协议
			 */
			toClose() {
				this.$refs.registerPopup.close();
			},
			async open() {
				await this.getInviteCode();
				if (!uni.getStorageSync('authInfo')) {
					uni.login({
						provider: 'weixin',
						timeout: 3000,
						success: res => {
							if (res.code) {
								this.$api.sendRequest({
									url: '/weapp/api/weapp/authcodetoopenid',
									data: {
										code: res.code
									},
									success: res => {
										if (res.code >= 0) {
											let authInfo = {};
											if (res.data.openid) authInfo.weapp_openid = res
												.data.openid;
											if (res.data.unionid) authInfo.wx_unionid = res
												.data.unionid;
											if (res.data.isauth) authInfo.isauth = res.data
												.isauth;
											this.isauth = res.data.isauth;
											uni.setStorageSync('authInfo', authInfo);
											this.$refs.receivePopup.open()
										} else {
											this.$util.showToast({
												title: '小程序配置错误'
											});
										}
									}
								})
							}
						},
						fail: () => {
							this.$util.showToast({
								title: '请求失败'
							});
						}
					})
				} else {
					this.$refs.receivePopup.open()
				}
			},
			close() {
				this.$refs.receivePopup.close()
			},
			// 微信小程序获取手机号
			getPhoneNumber(e) {
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					this.authMobileData = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData
					};

					let authData = uni.getStorageSync('authInfo');
					if (authData) Object.assign(this.authMobileData, authData);
					if (uni.getStorageSync('suid')) this.authMobileData.suid = uni.getStorageSync('suid');

					this.$api.sendRequest({
						url: '/api/tripartite/getPhoneNumber',
						data: this.authMobileData,
						success: res => {
							if (res.code >= 0) {
								this.mobile = res.data.mobile;
								this.isauth = res.data.isauth;
							} else {
								this.mobile = '';
								this.$util.showToast({
									title: res.message
								});
							}
						}
					});
				}
			},
		}
	}
</script>

<style lang="scss">
	.content {
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 0rpx 0rpx;
		padding: 60rpx;
		position: relative;

		.part1 {
			display: flex;
			align-items: center;

			.logo-view {
				margin-left: 0rpx;
				width: 96rpx;
				height: 96rpx;
				border-radius: 48rpx;
			}

			.intro-view {
				margin-left: 20rpx;

				.welcome-view {
					font-size: 36rpx;
					font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: #020202;
					line-height: 50rpx
				}

				.dec-view {
					font-size: 24rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #999999;
					line-height: 33rpx;
				}
			}
		}

		.close-view {
			position: absolute;
			right: 43rpx;
			top: 44rpx;
			width: 25rpx;
			height: 25rpx;
		}

		.img-view {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.avatar-wrapper {
				margin-top: 50rpx;
				padding: 0rpx;
				width: 128rpx;
				height: 128rpx;
				border-radius: 64rpx;

				.avatar {
					min-width: 128rpx;
					max-width: 128rpx;
					height: 128rpx;
					border-radius: 64rpx;
				}
			}
		}

		.name-view {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 88rpx;
			margin-top: 40rpx;
			background: rgba(0, 0, 0, 0.04);
			border-radius: 44rpx;

			.name-input {
				text-align: center;
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #252525;
				line-height: 45rpx;
			}

			.placeholder-view {
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #999999;
				line-height: 45rpx;
			}
		}

		.name-mobile {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 88rpx;
			margin-top: 40rpx;
			background: rgba(0, 0, 0, 0.04);
			border-radius: 44rpx;

			.mobile-input {
				text-align: center;
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #252525;
				line-height: 45rpx;
			}

			.placeholder-view {
				font-size: 32rpx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #FF4544;
				line-height: 45rpx;
			}
		}

		.login-but {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 88rpx;
			border-radius: 44px;
			margin-top: 50rpx;

			font-size: 32rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
			line-height: 45rpx;

			&.active {
				opacity: 1;
			}

			&.normal {
				opacity: 0.4;
			}
		}

		.agreement-view {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 60rpx;

			.select-image-view {
				width: 34rpx;
				height: 34rpx;
				margin-right: 18rpx;
			}

			.text {
				margin-top: -1rpx;
				font-size: 24rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #999999;
				line-height: 33rpx;

				&.agreement {
					color: #278AD6;
				}
			}
		}
	}

	.conten-box {
		padding: 0 30rpx 30rpx;

		.title {
			text-align: center;
			margin-top: 50rpx;
			margin-bottom: 10rpx;
		}

		.close {
			position: absolute;
			right: 30rpx;
			top: 10rpx
		}

		.con {
			height: 500rpx
		}
	}
</style>